package com.bruip.controller;

import com.bruip.dao.EmployeeDao;
import com.bruip.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Collection;

/**
 * @author 王若龙
 * @CreateTime 2022-09-06 14:34
 */
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    @GetMapping("/employee")
    public ModelAndView getAll() {
        ModelAndView modelAndView = new ModelAndView();
        Collection<Employee> allEmployee = employeeDao.getAll();
        modelAndView.addObject("allEmployee", allEmployee);
        modelAndView.setViewName("employee_list");
        return modelAndView;
    }

    @PostMapping("employee")
    public String addEmployee(Employee employee) {
        employeeDao.save(employee);
        //重定向至页表功能
        return "redirect:/employee";
    }

    @GetMapping("/employee/{id}")
    public String toUpdate(@PathVariable("id") Integer id, Model model){
        Employee employee = employeeDao.get(id);
        model.addAttribute("employee", employee);
        return "employee_update";
    }

    @PutMapping("employee")
    public String updateEmployee(Employee employee) {
        employeeDao.save(employee);
        //重定向至页表功能
        return "redirect:/employee";
    }

    @DeleteMapping("/employee/{id}")
    public String delete(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/employee";
    }
}
